import re

def parse_arrays_from_text(text):
    """
    从粘贴的文本中提取所有 [0, 0, 0, 1, ...] 格式的数组
    """
    pattern = re.compile(r'\[(.*?)\]', re.DOTALL)
    matches = pattern.findall(text)
    nalu_list = []

    for match in matches:
        # 去除换行和空格，转为整数数组
        nums = match.strip().replace('\n', '').split(',')
        try:
            nums = [int(num.strip()) for num in nums if num.strip()]
            nalu_list.append(nums)
        except ValueError:
            print("⚠️ 跳过了无法解析的数组：", match)
    return nalu_list

def write_h264_file(nalu_list, output_path='output_reconstructed.h264'):
    with open(output_path, 'wb') as f:
        for nalu in nalu_list:
            f.write(bytes(nalu))
    print(f"✅ 写入完成: {output_path}")

def main(input_txt_file):
    with open(input_txt_file, 'r', encoding='utf-8') as f:
        lines = f.readlines()

    array_lines = [line.strip() for line in lines if '[' in line and ']' in line and '//' not in line]


    # 拼成一个大字符串用于后续正则解析
    text = '\n'.join(array_lines)

    nalus = parse_arrays_from_text(text)
    if nalus:
        write_h264_file(nalus, 'output_reconstructed.h264')
    else:
        print("❌ 未识别到任何 NALU 数据")

if __name__ == '__main__':
    main("NALU数组.txt")
